#include "playwindow.h"
#include "ui_playwindow.h"
#include "globalresource.h"
#include <QPainter>

PlayWindow::PlayWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PlayWindow)
{
#ifdef  Debug_Falg
    qDebug() << "The name is : <" << __func__ << "> The file is :<" << __FILE__ << ">Thread is <" << QThread::currentThreadId();
#endif
    ui->setupUi(this);
    win_width_ = width();
    win_height_ = height();
    memset(&dst_video_frame_, sizeof(VideoFrame), 0);
    play_state_ = 2;
}

PlayWindow::~PlayWindow()
{
    delete ui;
}

int PlayWindow::Draw(const Frame *frame)
{
//#ifdef  Debug_Falg//循环
//    qDebug() << "The name is : <" << __func__ << "> The file is :<" << __FILE__ << ">Thread is <" << QThread::currentThreadId();
//#endif
    // 使用互斥锁保证线程安全，防止多线程同时访问共享资源
    QMutexLocker locker(&m_mutex);

    // 检查图像缩放器是否未初始化或需要重新调整大小
    if(!img_scaler_ || req_resize_) {
        // 如果图像缩放器已存在，先释放相关资源
        if(img_scaler_) {
            DeInit();
        }

        // 更新窗口的宽度和高度
        win_width_ = width();
        win_height_ = height();

        // 记录视频帧的宽度和高度
        video_width = frame->width;
        video_height = frame->height;

        // 创建一个新的图像缩放器对象
        img_scaler_ = new ImageScaler();

        // 计算视频帧的宽高比
        double video_aspect_ratio = frame->width * 1.0 / frame->height;
        // 计算窗口的宽高比
        double win_aspect_ratio = win_width_ * 1.0 / win_height_;

        if(win_aspect_ratio > video_aspect_ratio) {
            // 窗口宽高比大于视频宽高比，以窗口高度为基准调整图像尺寸
            img_height = win_height_;
            // 确保图像高度为 4 的倍数
            img_height &= 0xfffc;
            // 根据视频宽高比计算图像宽度
            img_width = img_height * video_aspect_ratio;
            // 确保图像宽度为 4 的倍数
            img_width &= 0xfffc;
            // 图像垂直居中显示
            y_ = 0;
            // 计算图像水平居中的起始位置
            x_ = (win_width_ - img_width) / 2;
        } else {
            // 窗口宽高比小于等于视频宽高比，以窗口宽度为基准调整图像尺寸
            img_width = win_width_;
            // 确保图像宽度为 4 的倍数
            img_width &= 0xfffc;
            // 根据视频宽高比计算图像高度
            img_height = img_width / video_aspect_ratio;
            // 确保图像高度为 4 的倍数
            img_height &= 0xfffc;
            // 图像水平居中显示
            x_ = 0;
            // 计算图像垂直居中的起始位置
            y_ = (win_height_ - img_height) / 2;
        }

        // 初始化图像缩放器，设置输入和输出的尺寸、格式
        img_scaler_->Init(video_width, video_height, frame->format,
                          img_width, img_height, AV_PIX_FMT_RGB24);

        // 初始化目标视频帧结构体
        memset(&dst_video_frame_, 0, sizeof(VideoFrame));
        // 设置目标视频帧的宽度
        dst_video_frame_.width = img_width;
        // 设置目标视频帧的高度
        dst_video_frame_.height = img_height;
        // 设置目标视频帧的像素格式为 RGB24
        dst_video_frame_.format = AV_PIX_FMT_RGB24;
        // 为目标视频帧的数据缓冲区分配内存
        dst_video_frame_.data[0] = (uint8_t*)malloc(img_width * img_height * 3);
        // 设置目标视频帧每行的字节数
        dst_video_frame_.linesize[0] = img_width * 3;

        // 重置尺寸调整标志
        req_resize_ = false;
    }

    // 调用图像缩放器对视频帧进行缩放处理
    img_scaler_->Scale3(frame, &dst_video_frame_);

    // 使用缩放后的视频帧数据创建一个临时 QImage 对象
    QImage imageTmp =  QImage((uint8_t *)dst_video_frame_.data[0],
                              img_width, img_height, QImage::Format_RGB888);
    // 复制临时 QImage 对象到成员变量 img 中
    img = imageTmp.copy(0, 0, img_width, img_height);

    // 请求更新窗口显示
    update();
    // 注释掉的 repaint() 函数，repaint() 会立即重绘，而 update() 是异步重绘
    //    repaint();

    return 0;
}

void PlayWindow::DeInit()
{
#ifdef  Debug_Falg
    qDebug() << "The name is : <" << __func__ << "> The file is :<" << __FILE__ << ">Thread is <" << QThread::currentThreadId();
#endif
    if(dst_video_frame_.data[0]) {
        free(dst_video_frame_.data[0]);
        dst_video_frame_.data[0] = NULL;
    }
    if(img_scaler_) {
        delete img_scaler_;
        img_scaler_ = NULL;
    }
}

void PlayWindow::StartPlay()
{
#ifdef  Debug_Falg
    qDebug() << "The name is : <" << __func__ << "> The file is :<" << __FILE__ << ">Thread is <" << QThread::currentThreadId();
#endif
    QMutexLocker locker(&m_mutex);
    play_state_ = 1;
}

void PlayWindow::StopPlay()
{
#ifdef  Debug_Falg
    qDebug() << "The name is : <" << __func__ << "> The file is :<" << __FILE__ << ">Thread is <" << QThread::currentThreadId();
#endif
    QMutexLocker locker(&m_mutex);
    play_state_ = 2;
    update();
}


void PlayWindow::paintEvent(QPaintEvent *)
{

    QMutexLocker locker(&m_mutex);
    if(play_state_ == 1) {  // 播放状态
        if (img.isNull()) {
            return;
        }
        QPainter painter(this);
        painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
        //    //    p.translate(X, Y);
        //    //    p.drawImage(QRect(0, 0, W, H), img);
        QRect rect = QRect(x_, y_, img.width(), img.height());
        //        qDebug() << rect << ", win_w:" << this->width() << ", h:" << this->height();
        painter.drawImage(rect, img.scaled(img.width(), img.height()));
    } else if(play_state_ == 2) {
        QPainter p(this);
        p.setPen(Qt::NoPen);
        p.setBrush(Qt::black);
        p.drawRect(rect());
    }
}


//void PlayWindow::paintEvent(QPaintEvent *)
//{
//    QMutexLocker locker(&m_mutex);
//    if(play_state_ == 1) {  // 播放状态
//        if (img.isNull()) {
//            return;
//        }
//        QPainter painter(this);
//        //        painter.setRenderHint(QPainter::Antialiasing, true);
//        painter.setRenderHint(QPainter::HighQualityAntialiasing);
//        int w = this->width();
//        int h = this->height();
//        img.scaled(w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation);
//        //    //    p.translate(X, Y);
//        //    //    p.drawImage(QRect(0, 0, W, H), img);
//        QRect rect = QRect(x_, y_, w, h);
//        painter.drawImage(rect, img);
//    } else if(play_state_ == 2) {
//        QPainter p(this);
//        p.setPen(Qt::NoPen);
//        p.setBrush(Qt::black);
//        p.drawRect(rect());
//    }
//}


void PlayWindow::resizeEvent(QResizeEvent *event)
{
    QMutexLocker locker(&m_mutex);
    if(win_width_ != width() || win_height_ != height()) {
        //        DeInit();       // 释放尺寸缩放资源，等下一次draw的时候重新初始化
        //        win_width = width();
        //        win_height = height();
        req_resize_ = true;
    }
}








//void Draw() {
//        AVPacket packet;
//        while (av_read_frame(formatContext, &packet) >= 0) {
//            if (packet.stream_index == videoStreamIndex) {
//                avcodec_send_packet(codecContext, &packet);
//                while (avcodec_receive_frame(codecContext, frame) == 0) {
//                    // 转换图像格式
//                    sws_scale(swsContext, (const uint8_t* const*)frame->data,
//                              frame->linesize, 0, codecContext->height,
//                              frameRGB->data, frameRGB->linesize);

//                    // 更新 SDL 纹理
//                    SDL_UpdateTexture(texture, nullptr, frameRGB->data[0], frameRGB->linesize[0]);

//                    // 清屏
//                    SDL_RenderClear(renderer);

//                    // 复制纹理到渲染器
//                    SDL_RenderCopy(renderer, texture, nullptr, nullptr);

//                    // 显示渲染内容
//                    SDL_RenderPresent(renderer);

//                    // 控制播放速度
//                    SDL_Delay(40);
//                }
//            }
//            av_packet_unref(&packet);
//        }
//    }


//int PlayWindow::Draw(const Frame *frame)
//{
//    QMutexLocker locker(&m_mutex);
//    if(!img_scaler_ || req_resize_) {
//        // 初始化和调整大小逻辑
//        img_scaler_ = new ImageScaler();
//        // 计算宽高比并调整图像尺寸
//        // 初始化图像缩放器和目标视频帧
//    }
//    // 调用图像缩放器对视频帧进行缩放处理
//    img_scaler_->Scale3(frame, &dst_video_frame_);
//    // 创建 QImage 对象
//    QImage imageTmp =  QImage((uint8_t *)dst_video_frame_.data[0],
//                              img_width, img_height, QImage::Format_RGB888);
//    img = imageTmp.copy(0, 0, img_width, img_height);
//    // 请求更新窗口显示
//    update();
//    return 0;
//}
